<?php
/**
 * Description: 真题收藏
 * User: devforma
 * Date: 15/4/16
 * Time: 11:03
 */

require __DIR__ . '/includes/utils.php';
class CollectQuestion implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb,$uddb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        $userId = $queryArgs['user_id'];

        if (empty($queryArgs['question_id']) || !is_numeric($queryArgs['question_id']) ||
            empty($queryArgs['type']))
            return genOutput(1000);

        //获取题目信息
        $qInfo = $cmsdb->getRow('SELECT * FROM `original_ztk_questions` WHERE `id`=:qid',
            array(':qid' => $queryArgs['question_id']));
        if (empty($qInfo))
            return genOutput(1000);

        //获取用户信息
        $uInfo = getUserData($userId);
        if (empty($uInfo))
            return genOutput(1000);

        if ($queryArgs['type'] == 'collect') { //收藏
            $qExists = $uddb -> usertestsTable($userId)->
            where(array('question_id' => $queryArgs['question_id'],'user_id' => $userId))->value('id');
            if (empty($qExists)) {
                $uddb -> usertestsTable($userId)->insert(array(
                    'user_id' => $userId,
                    'question_id' => $queryArgs['question_id'],
                    'note_id' => $qInfo->note_id,
                    'testarea_id' => $uInfo->exam_detail_id,
                    'category_id' => getQuestionCategory($qInfo->category),
                    'user_answer' => '',
                    'is_collected' => 1,
                    'collect_time' => date('Y-m-d H:i:s')
                ));
            } else {
                $uddb -> usertestsTable($userId)
                    ->where(array('user_id' => $userId, 'question_id' => $queryArgs['question_id']))
                    ->update(array('is_collected' => 1, 'collect_time' => date('Y-m-d H:i:s')));
            }

        } elseif ($queryArgs['type'] == 'cancel') { //取消收藏
            $uddb -> usertestsTable($userId)
                ->where( array(
                    'user_id' => $userId,
                    'question_id' => $queryArgs['question_id'],
                    'is_collected' => 1
                ))
                ->update(array('is_collected' => 2)
                );

        } else {
            return genOutput(1000);
        }

        return genOutput(1);
    }
}